package cn.tedu.homework_weibo.controller;

import cn.tedu.homework_weibo.common.JsonResult;
import cn.tedu.homework_weibo.common.StatusCode;
import cn.tedu.homework_weibo.mapper.UserMapper;
import cn.tedu.homework_weibo.pojo.dto.UserLoginDTO;
import cn.tedu.homework_weibo.pojo.dto.UserRegDTO;
import cn.tedu.homework_weibo.pojo.entity.User;
import cn.tedu.homework_weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@RestController
@Slf4j
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO) {
        log.debug("UserRegDTO: " + userRegDTO);
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null) {//用户名已经存在
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXIST);
        }
        //注册新用户
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();
    }

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO = " + userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) {//用户名不存在
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userVO.getPassword().equals(userLoginDTO.getPassword())) {//密码正确
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
    }

    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        // 获取session中的用户信息
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }
    @ApiOperation("退出登录")
    @GetMapping("logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
